import useCat from "../store/useCat";
import {useShallow} from 'zustand/shallow';


const Cat1 = () => {
    console.log('cat1 render');
    const {name,age,addAge,setName}  = useCat(); 
    return (
        <div style={{border:'1px solid red', width:300, padding:20}}>
            <h2>Cat1</h2>
            <p>name: {name}</p>
            <p>age: {age}</p>
            <p style={{color:'red'}}>{Math.random()}</p>
            <button onClick={addAge}>修改年龄</button>
            <button onClick={setName}>修改名称</button>
        </div>
    )
}

const Cat2 = () => {
    console.log('cat2 render');
    // const {name,color}  = useCat();  // @1 每次都重新渲染，性能差

    const {name,color}  = useCat(useShallow (state =>({name:state.name,color:state.color}))); // @2 采用 useShallow 进行简写，可以返回多个

    // @3 不采用useShallow, 一个个来处理,太多了会很繁琐，多了建议用useShallow，不多直接使用
    // const name = useCat(state => state.name); 
    // const color = useCat(state => state.color); 

    return (
        <div style={{border:'1px solid red', width:300, padding:20,margin:'0 20px'}}>
            <h2>Cat2</h2>
            <p>name: {name}</p>
            <p>color: {color}</p>
            <p style={{color:'blue'}}>{Math.random()}</p>
        </div>
    )
}


const Cat3 = () => {
    console.log('cat3 render');
    const addAge  = useCat(state => state.addAge); 
    const restState  = useCat(state => state.restState); 
    return (
        <div style={{border:'1px solid red', width:300, padding:20}}>
            <h2>Cat3</h2>
            <p>  </p>
            <p style={{color:'green'}}>{Math.random()}</p>
           <button onClick={addAge}>修改年龄</button>

           {/* 
                因为状态在内容里面，你清空缓存数据，再次操作会基于内容的状态修改，
                所以，清空缓存数据，首先把状态初始化后，在进行清空缓存数据 useCat.persist.clearStorage();

           */}
           <button onClick={restState}>清空缓存数据</button>
        </div>
    )
}

const Cat = () => {
    return (
        <div  style={{display:'flex', just:'space-between', width:'100%'}}>
            <Cat1 />
            <Cat2 />
            <Cat3 />
        </div>
    )
}

export default Cat;